<template>
  <el-card style="max-width: 600px; margin: 50px auto;">
    <template #header>
      <div style="text-align: center;">
        <h2>修改用户信息</h2>
      </div>
    </template>
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="用户ID" prop="UserId">
        <el-input v-model="formData.UserId" disabled />
      </el-form-item>
      
      <el-form-item label="用户名" prop="UserName">
        <el-input v-model="formData.UserName" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="昵称" prop="NickName">
        <el-input v-model="formData.NickName" placeholder="请输入昵称" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="UserEmail">
        <el-input v-model="formData.UserEmail" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="密码" prop="Password">
        <el-input 
          v-model="formData.Password" 
          type="password" 
          placeholder="请输入新密码（留空则不修改）" 
          show-password 
        />
      </el-form-item>
      
      <el-form-item label="角色" prop="RoleId">
        <el-select v-model="formData.RoleId" placeholder="请选择角色" style="width: 100%;">
          <el-option
            v-for="role in roles"
            :key="role.RoleId"
            :label="role.RoleName"
            :value="role.RoleId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import axios from 'axios';

interface User {
  UserId: number;
  UserName: string;
  NickName: string;
  UserEmail: string;
  Password?: string;
  RoleId: number;
}

interface Role {
  RoleId: number;
  RoleName: string;
}

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();

const formData = ref<User>({
  UserId: 0,
  UserName: '',
  NickName: '',
  UserEmail: '',
  Password: '',
  RoleId: 0
});

const roles = ref<Role[]>([]);

const rules = ref<FormRules>({
  UserName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
  ],
  NickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '昵称长度在1到20个字符', trigger: 'blur' }
  ],
  UserEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  RoleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
});

// 获取用户详情
const getUserDetail = () => {
  axios({
    url: "http://localhost:5028/api/Management/GetUserDetail",
    method: "get",
    params: { UserId: route.params.id }
  })
  .then(res => {
    console.log('用户详情:', res);
    if (res.data.Code === 200) {
      formData.value = res.data.Result;
      // 确保RoleId有默认值
      if (!formData.value.RoleId) {
        formData.value.RoleId = 0;
      }
    } else {
      ElMessage.error('获取用户信息失败');
    }
  })
  .catch(error => {
    console.error('获取用户详情失败:', error);
    ElMessage.error('获取用户信息失败');
  });
};

// 获取角色列表
const getRoles = () => {
  axios({
    url: "http://localhost:5028/api/Management/GetRoleItem",
    method: "get"
  })
  .then(res => {
    console.log('角色列表:', res);
    if (res.data.Code === 200) {
      roles.value = res.data.Result.map((item: any) => ({
        RoleId: item.value,
        RoleName: item.label
      }));
      // 添加请选择选项
      roles.value.unshift({ RoleId: 0, RoleName: '请选择' });
    }
  })
  .catch(error => {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  });
};

// 提交表单
const submitForm = () => {
  if (!formRef.value) return;
  
  formRef.value.validate((valid: boolean) => {
    if (!valid) {
      ElMessage.error('请填写完整信息');
      return;
    }
    
    // 如果密码为空，则不发送密码字段
    const submitData = { ...formData.value };
    if (!submitData.Password) {
      delete submitData.Password;
    }
    
    axios({
      url: "http://localhost:5028/api/Management/UpdateUser",
      method: "put",
      data: submitData
    })
    .then(res => {
      console.log('修改结果:', res);
      if (res.data.Code === 200) {
        ElMessage.success('修改成功');
        router.push('/show-user');
      } else {
        ElMessage.error(res.data.Message || '修改失败');
      }
    })
    .catch(error => {
      console.error('修改失败:', error);
      if (error.response?.data?.Message) {
        ElMessage.error(error.response.data.Message);
      } else {
        ElMessage.error('修改失败');
      }
    });
  });
};

// 返回
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  getUserDetail();
  getRoles();
});
</script>

<style scoped>
.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}
</style>